package com.example.cash.craft.security;

import cn.hutool.json.JSONUtil;
import com.example.cash.craft.web.JsonResult;
import com.example.cash.craft.web.StateCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义认证失败处理器（响应未登录的错误信息）
 */
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        log.error("认证失败：{}", authenticationException);
        response.setContentType("application/json; charset=UTF-8");
        String message = "您当前没有登录，或登录已过期";
        JsonResult<Void> jsonResult = JsonResult.fail(StateCode.ERROR_UNAUTHORIZED, message);
        String jsonString = JSONUtil.toJsonStr(jsonResult);
        PrintWriter writer = response.getWriter();
        writer.println(jsonString);
        writer.close();
    }

}
